//
//  QCSetupSlider.swift
//  爱汽车
//
//  Created by tucici on 2023/8/27.
//

import UIKit

struct QCSetupSliderMode{
    var thumImg:String = ""
    var limit = (min:0, max:0)
    var current = (left:0,right:0)
    var target = (left:0,right:0)
    ///目标高度显示时间，0，不显示，1，一直显示，>1，显示多长后，消失
    var showSelectTime:Int? = 0
    ///档位
    var dangwei:Int?=0
}
class QCSetupSlider: UIView {
    @IBOutlet var line: UIView!
    @IBOutlet var maxValue: UILabel!
    @IBOutlet var rightImg: UIImageView!
    @IBOutlet var leftImg: UIImageView!
    @IBOutlet var thumImg: UIImageView!
    @IBOutlet var currentValue: UILabel!
    @IBOutlet var rightImg_select: UIImageView!
    @IBOutlet var leftImg_select: UIImageView!
    @IBOutlet var lineWidth: NSLayoutConstraint!
    @IBOutlet var rightImgBottom: NSLayoutConstraint!
    @IBOutlet var leftImgBottom: NSLayoutConstraint!
    @IBOutlet var thumImgW: NSLayoutConstraint!
    @IBOutlet var maxValueH: NSLayoutConstraint!
    @IBOutlet var rightImg_select_Bottom: NSLayoutConstraint!
    @IBOutlet var leftImg_select_Bottom: NSLayoutConstraint!
    ///档位旧值
    private var old_dangwei:Int?=1000
    private var displayLink : CADisplayLink?
    ///档位显示开始时间戳
    private var dangwei_startTime : CGFloat = 0.0
    override func awakeFromNib() {
        super.awakeFromNib()
        ///不需要滑动效果，注释掉
        //let pan2 = UIPanGestureRecognizer(target:self, action:#selector(actionForPan))
        //self.addGestureRecognizer(pan2)
        NotificationCenter.default.addObserver(self, selector: #selector(updateDangwei), name: NSNotification.Name("updateDangwei"), object: nil)
    }
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    var type = QCSetupSliderMode(){
        didSet{
            maxValue.isHidden = type.thumImg == ""
            thumImg.isHidden = type.thumImg == ""
            leftImg.isHidden = !thumImg.isHidden
            rightImg.isHidden = !thumImg.isHidden
            currentValue.isHidden = thumImg.isHidden
            
            maxValueH.constant = type.thumImg == "" ? 0 : 14
            thumImgW.constant = type.thumImg == "" ? 0 : 25
            thumImg.image = type.thumImg == "" ? nil : UIImage(named: type.thumImg)
            maxValue.text = "\(type.limit.max)"
            
            ///实际高度
            let s_l =  CGFloat(min(type.current.left, type.limit.max)) / CGFloat(type.limit.max)
            let s_r =  CGFloat(min(type.current.right, type.limit.max)) / CGFloat(type.limit.max)
            //            let s_r = 0.3
            //            let s_l = 0.3
            leftImgBottom.constant = s_l * line.bounds.height - leftImg.bounds.height/2.0
            rightImgBottom.constant = s_r * line.bounds.height - rightImg.bounds.height/2.0
            //            currentValue.text = String(format:"%.0f", (Double("\(type.max)") ?? 0) * type.l_current)
            currentValue.text = String(format:"%d", type.current.left)
            animateBarHeight(s_l, s_r)
            
            ///目标高度显示
            let t_l =  CGFloat(min(type.target.left, type.limit.max)) / CGFloat(type.limit.max)
            let t_r = CGFloat(min(type.target.right, type.limit.max)) / CGFloat(type.limit.max)
            leftImg_select_Bottom.constant = t_l * line.bounds.height - leftImg_select.bounds.height/2.0
            rightImg_select_Bottom.constant = t_r * line.bounds.height - rightImg_select.bounds.height/2.0
            switch (type.showSelectTime ?? 0){
            case 0 :
                leftImg_select.isHidden = true
                rightImg_select.isHidden = true
                displayLink?.invalidate()
            case 1:
                leftImg_select.isHidden = false
                rightImg_select.isHidden = false
                displayLink?.invalidate()
            case 5...:
                ///换档位时候，目标显示showSelecttime后消失
                if old_dangwei != type.dangwei && type.dangwei ?? 0 > 0{
                    updateDangwei()
                }
            default:
                break
            }
            
            
            ///新增特殊情况：新增气压记忆模式，隐藏所有箭头
            if isPressureMode {
                leftImg.isHidden = true
                rightImg.isHidden = true
                leftImg_select.isHidden = true
                rightImg_select.isHidden = true
            }
            
        }
    }
    
    
    ///渐变色layer
    lazy var color_layer:CAGradientLayer = {
        let layer = CAGradientLayer()
        layer.colors = ["#FF5733".color().cgColor,"#00BAAD".color().cgColor]
        layer.locations = [0, 1]
        layer.startPoint = CGPoint(x:0, y: 0)
        layer.endPoint = CGPoint(x: 0, y: 1)
        layer.mask = bg_shape
        line.layer.addSublayer(layer)
        return layer
    }()
    
    ///背景条形柱状
    lazy var bg_shape:CAShapeLayer = {
        let layer = CAShapeLayer()
        layer.fillColor = "#20242E".color().cgColor
        line.layer.addSublayer(layer)
        return layer
    }()
    
    ///渐变色色组，默认蓝到橙渐变
    var gradientHexColors = ["#FF5733","#00BAAD"]{
        didSet{
            let colors = gradientHexColors.map { $0.color().cgColor}
            color_layer.colors = colors.count <= 0 ? ["#FF5733".color().cgColor,"#00BAAD".color().cgColor] : colors
        }
    }
    ///是否显示渐变色，默认显示
    var showGradientColor = true{
        didSet{
            color_layer.isHidden = !showGradientColor
            if showGradientColor {
                color_layer.mask = bg_shape
                line.layer.addSublayer(color_layer)
            }else{
                color_layer.mask = nil
                line.layer.addSublayer(bg_shape)
            }
        }
    }
    
    ///更新档位
    @objc func updateDangwei(){
        old_dangwei = type.dangwei
        ///当是高度模式的时候，换挡的时候，中上和中下，要先显示，再慢慢的变透明
        ///左边和右边的，则排除，不显示
        if !isPressureMode && type.thumImg == "" {
            leftImg_select.isHidden = false
            rightImg_select.isHidden = false
            leftImg_select.alpha = 1
            rightImg_select.alpha = 1
        }
        
        dangwei_startTime = CACurrentMediaTime()
        if let diplay = displayLink{
            diplay.invalidate()
        }
        displayLink = CADisplayLink(target: self, selector: #selector(updateDisplay))
        displayLink?.add(to: .main, forMode: .common)
    }
    
    
    @objc func actionForPan(_ pan:UIPanGestureRecognizer){
        let location = pan.location(in: self)
        let value = Int((self.bounds.height - location.y) / self.bounds.height * CGFloat(type.limit.max))
        if value > type.limit.max || value < type.limit.min {return}
        type.current = (left:value,right:value)
    }
    
    ///目标高度逐渐消失
    @objc func updateDisplay(){
        let currentTime = CACurrentMediaTime() - dangwei_startTime
        let progress = min(currentTime / Double(type.showSelectTime ?? 1), 1.0) // 计算动画进度，限制在 0 到 1 之间
        // 根据动画进度更新透明度或其他属性
        let alpha = 1.0 - progress
        leftImg_select.alpha = alpha
        rightImg_select.alpha = alpha
        if currentTime >= Double(type.showSelectTime ?? 1){
            displayLink?.invalidate() // 动画完成后停止 CADisplayLink
        }
    }
    
    ///条形柱状，高度动画
    func animateBarHeight(_ scale_left: CGFloat, _ scale_right:CGFloat) {
        color_layer.frame = line.bounds
        bg_shape.frame = line.bounds
        
        let scale = max(scale_left, scale_right)
        let offsetY = bg_shape.bounds.height * scale
        let newPath = UIBezierPath(roundedRect:CGRect(x:0, y:bg_shape.frame.height - offsetY, width:bg_shape.frame.width, height:offsetY),
                                   byRoundingCorners:[.topLeft,.topRight,.bottomLeft,.bottomRight],
                                   cornerRadii:CGSize(width:bg_shape.bounds.width/2, height: bg_shape.bounds.width/2))
        
        let oldPath = UIBezierPath(roundedRect:CGRect(x:0, y: 0, width:bg_shape.bounds.width, height: bg_shape.bounds.height),
                                   byRoundingCorners:[.topLeft,.topRight,.bottomLeft,.bottomRight],
                                   cornerRadii:CGSize(width:bg_shape.bounds.width/2, height:bg_shape.bounds.width/2))
        
        let animation = CABasicAnimation(keyPath: "path")
        animation.fromValue = oldPath.cgPath
        animation.toValue = newPath.cgPath
        animation.duration = 0.01 // 动画持续时间，可以根据需要进行调整
        animation.fillMode = .forwards
        animation.isRemovedOnCompletion = false
        bg_shape.removeAnimation(forKey: "pathAnimation")
        bg_shape.add(animation, forKey: "pathAnimation")
    }
}

